package Ep06_BinaryTree.BT28_0235;

import Ep06_BinaryTree.TreeNode;

/**
 * @author Jimmy Zhan WORKSTATION
 * @date 2023/7/9 14:13
 * 说明： 同 236一样的解法
 */

public class Mine {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) return null;
        if (root == p || root == q) return root;

        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);

        if (left == null && right == null) return null;
            // 不是 return root.right 或 return root.left, 而是 return left 或 return right
            // 因为我们要把节点的信息（左右分别有没有p或q）一层一层地向上传递，如果root.left/right传递的仅仅只是当前节点的左右孩子
        else if (left == null && right != null) return right;
        else if (right == null && left != null) return left;
        else if (left != null && right != null) return root;
        else return null;
    }
}
